part of _;

extension Controller on MainPage {
  void controller_checkNetLines({bool log = false}) async {
    var resultIndex = 0;
    var resultTime = YConfig.timeOut;
    final ipsStr = await yRead(IFinal.Saves.lines);
    final results = ipsStr!.split(",");
    if (results.length <= 1) return;
    final dio = Dio();
    dio.options.connectTimeout = Duration(milliseconds: YConfig.timeOut);
    dio.options.receiveTimeout = Duration(milliseconds: YConfig.timeOut);
    dio.options.sendTimeout = Duration(milliseconds: YConfig.timeOut);
    String linesResult = "";
    for (var i = 0; i < results.length; i++) {
      final ip = results[i];
      try {
        var startTime = DateTime.now().millisecondsSinceEpoch;
        var response = await dio.post(ip + IFinal.Urls.interface, data: {"jkid": IFinal.Jkids.checkLine});
        var endTime = DateTime.now().millisecondsSinceEpoch;
        if (response.statusCode == 200) {
          if (response.data["root"]["code"] == "1") {
            if (endTime - startTime < resultTime) {
              resultTime = endTime - startTime;
              linesResult += "线路${i + 1}，地址：$ip，心跳耗时：$resultTime，比较结果：faster\n";
              resultIndex = i;
            } else {
              linesResult += "线路${i + 1}，地址：$ip，心跳耗时：${endTime - startTime}，比较结果：slower\n";
            }
          }
        }
      } catch (e) {
        linesResult += "线路${i + 1}，地址：$ip，心跳错误：${e.toString()}\n";
      }
    }
    linesResult += "本轮扫描时间：${DateTime.now()}，最优结果：线路${resultIndex + 1}\n";
    ySave(IFinal.Saves.linesResult, linesResult);
    if (log) yLog(linesResult);
    ySave(IFinal.Saves.linesIndex, resultIndex.toString());
    IFinal.Others.BaseIP = (resultIndex + 1 > IFinal.Configs_Server.lines.length) ? IFinal.Configs_Server.lines.first : IFinal.Configs_Server.lines[resultIndex];
    yConfigIP(IFinal.Others.BaseIP + IFinal.Urls.interface);
    yConfigUpdateIP(YConfig.IP);
    yRun(() => controller_checkNetLines(), delay: 60000);
  }

  void controller_reloadHome() {
    setState(() {});
    pages.forEach((page) {
      final yPage = page.onCreateState.call();
      if (yPage.mounted && yPage.yIsAlive) yPage.setState(() {});
    });
  }

  void controller_doScheme() async {
    AppUtils.switchScheme(yPage, await AppPlugin.getSchemeData(), showErrorToast: false);
  }

  void controller_registerBroadCast() {
    yBroadcast_register(IFinal.Broadcasts.refreshHomeTJShowType, (map) {
      yRead(IFinal.Saves.productListIsGrid).then((productListIsGrid) {
        IFinal.Others.isProductShowGrid = (productListIsGrid != null && productListIsGrid == "true");
        controller_reloadHome();
      });
    });
    yBroadcast_register(IFinal.Broadcasts.refreshCart, (map) {
      mainPage_cart.controller?.loadData();
    });
  }

  void controller_loginYIM() async {
    YIM.userManager.logout();
    if (globalUserModel == null) return;
    YIM.userManager.login(
      user: globalUserModel!.yim_user,
      token: globalUserModel!.yim_token,
      callback: (result) {
        if (result.code != YIMEnum_LoginResult.Success) {
          yRun(() => controller_loginYIM(), delay: 2000);
          return;
        }
        controller_queryRecentConversations();
      },
    );
    YIM.listenerManager.register_status_online(callback: (result) {
      switch (result.code) {
        case YIMEnum_OnlineState.Reconnecting:
          controller_queryRecentConversations();
          break;
        case YIMEnum_OnlineState.Reconnected:
          controller_queryRecentConversations();
          break;
        case YIMEnum_OnlineState.Kick:
          yShowBuilder("您的账号在其他设备登录", () {
            AppUtils.reLaunchApp(goLogin: true);
          }, null, false, posTitle: "重新登录");
          break;
      }
    });
    YIM.listenerManager.register_recentConversation(callback: () {
      controller_queryRecentConversations();
    });
    YIM.listenerManager.register_revoke(callback: (message) {
      yBroadcast_send(IFinal.Broadcasts.onRecRevoke, params: {"message": message});
    });
    YIM.listenerManager.register_status_msg_receipt(callback: (conversationID) {
      yBroadcast_send(IFinal.Broadcasts.onRecReceipt, params: {"conversationID": conversationID});
    });
    YIM.listenerManager.register_message(callback: (messages) {
      Vibration.vibrate();
      MessageUtils.onRecMessage(page: this, messages: messages);
      yBroadcast_send(IFinal.Broadcasts.onRecMessage, params: {"messages": messages});
    });
  }

  void controller_queryRecentConversations() {
    YIM.conversationManager.queryRecentConversation(callback: (conversations) async {
      if (conversations == null) {
        badge_message_count = 0;
        controller_reloadHome();
        return;
      }
      var unReadCount = 0;
      if (mainPage_message.conversations == null) mainPage_message.conversations = [];
      mainPage_message.conversations?.clear();
      for (final conversation in conversations) {
        try {
          mainPage_message.conversations?.add(ConversationModel.fromYIMConversation(conversation, conversation.lastMessage!.from == globalUserModel!.yim_user));
          unReadCount += conversation.unRead;
        } catch (e) {}
      }
      badge_message_count = unReadCount;
      mainPage_message.refresherController?.loadFinish(showNoMoreData: mainPage_message.conversations?.isEmpty ?? true);
      controller_reloadHome();
    });
  }
}
